import router from '@/router'
import { userStore } from '@/stores'
import axios, { AxiosError, type Method } from 'axios'
import { showToast } from 'vant'

// 1. 新axios实例，基础配置
const instance = axios.create({
  baseURL: 'https://consult-api.itheima.net',
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    // 2. 携带token
    const store = userStore()
    if(store.user?.token && config.headers){
      config.headers['Authorization'] = `Bearer ${store.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // 3. 处理业务失败
    if(res.data.code !== 10000){
      showToast({message:res.data.message || '业务失败'})
      return Promise.reject(res.data)
    }
    // 4. 摘取核心响应数据
    return res.data
  },
  (err:AxiosError) => {
    // TODO 5. 处理401错误
    if(err.response?.status === 401){
      // 获取用户仓库，删除用户信息
      const store = userStore()
      store.delUser()
      router.push({
        path:'/login',
        query: { returnUrl : router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

type Data<T> = {
  code : number
  message : string
  data : T
}

export default instance

// 4. 请求工具函数
export const request = <T>(url: string, method: Method = 'get', submitData?: object) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
